package lesson19.notepad;

import java.util.Scanner;

public class SecuredNotepad2 implements INotepad {

	Scanner sc = new Scanner(System.in);

	Page[] securedNotepad;
	String password;

	SecuredNotepad2(final String password, int numberOfPages) {
		if (numberOfPages > 0)
			this.securedNotepad = new Page[numberOfPages];
		else
			this.securedNotepad = new Page[20];

		if (password != null && password != "") {
			this.password = password;
		} else
			System.out
					.println("Wrong password format! Please restart the app!");

		for (int i = 0; i < securedNotepad.length; i++) {
			securedNotepad[i] = new Page(String.valueOf(i + 1));
		}
	}

	@Override
	public void addText(final String addedText, final int page) {

		if (validatePass()) {
			if (validatePage(page)) {
				if (addedText != null) {
					securedNotepad[page - 1].addText(addedText);
				} else
					System.out
							.println("Wrong text format! Please restart the app!");
			}
		}
	}

	private boolean validatePass() {
		System.out.println("Enter password: ");
		String pass = sc.nextLine();
		return pass.equals(this.password);
	}

	private boolean validatePage(int page) {
		return page > 0 && page <= securedNotepad.length;
	}

	@Override
	public void overwriteText(final String newText, final int page) {

		if (validatePass() == true) {
			if (validatePage(page))
				if (newText != null) {
					securedNotepad[page - 1].deleteText();
					securedNotepad[page - 1].addText(newText);
				} else
					System.out
							.println("Wrong text format! Please restart the app!");
		}
	}

	@Override
	public void deleteText(final Page selectedPage) {

		if (validatePass() == true) {
			if (selectedPage != null) {
				for (int i = 0; i < securedNotepad.length; i++)
					if (securedNotepad[i].equals(selectedPage))
						selectedPage.deleteText();
			}
		}

	}

	@Override
	public void printPages() {
		if (validatePass() == true) {
			for (int i = 0; i < securedNotepad.length; i++) {
				if (securedNotepad[i] != null)
					securedNotepad[i].printPageInfo();
			}
		}
	}

}
